<template>
  <div style="padding: 10px">
    <el-card style="padding:10px;background:#EBEEF5">
      <div style="margin: 10px 0;width: 100%">
        <el-button type="primary" :icon="CirclePlus" @click="add">新增</el-button>
        <el-button type="danger" :icon="Remove" @click="Show" v-if="!isShow">批量删除</el-button>
        <el-button type="danger" :icon="Remove" @click="deleteBatch" v-if="isShow">删除</el-button>
        <el-button type="danger" :icon="CircleClose"  @click="Show" v-if="isShow">取消</el-button>
        <el-upload     action="http://localhost:9090/orders/import"   :on-success="handleUploadSuccess"   :show-file-list=false   :limit="1"   accept='.xlsx'   style="display: inline-block; margin: 0 10px" >
          <el-button type="primary" :icon="Download">导入</el-button>
        </el-upload>
        <el-button :icon="Upload"  type="primary" @click="exportOrders">导出</el-button>

        <el-input v-model="no" placeholder="请输入订单号" style="width: 15%;margin: 0 10px 0 50px" clearable/>
        <el-input v-model="username" placeholder="请输入购买人" style="width: 15%;" clearable/>
        <el-button type="primary" :icon="Search" style="margin-left: 10px" @click="load">查询</el-button>
        <el-button type="primary" :icon="Refresh" style="margin-left: 10px" @click="reset">重置</el-button>
      </div>
    <el-table

        :data="tableData"
        :row-style="tableRowStyle" :cell-style="{'text-align':'center'}" :header-cell-style="{'text-align':'center'}"
        border resizable="true"
        style="width: 100%"
        @selection-change="handleSelectionChange"
    >
      <el-table-column v-if="isShow" type="selection" width="55"></el-table-column>
      <el-table-column prop="id" label="ID" width="80" sortable></el-table-column>
      <el-table-column prop="no" label="订单编号"></el-table-column>
      <el-table-column prop="name" label="名称"></el-table-column>
      <el-table-column prop="time" label="订单时间"></el-table-column>
      <el-table-column prop="state" label="支付状态"></el-table-column>
      <el-table-column prop="total" label="订单总价"></el-table-column>
      <el-table-column prop="paymentTime" label="支付时间"></el-table-column>
      <el-table-column prop="alipayNo" label="支付宝宝流水号"></el-table-column>
      <el-table-column prop="returnTime" label="退款时间"></el-table-column>
      <el-table-column prop="userName" label="购买者"></el-table-column>
<!--      <el-table-column label="支付"  width="180" align="center">-->
<!--        <template v-slot="scope">-->
<!--          <el-button type="primary" @click="pay(scope.row)" :disabled="scope.row.state !== '待支付'">支 付</el-button>-->
<!--          <el-button type="danger" @click="returnPay(scope.row)" :disabled="scope.row.state !== '已支付'">退款</el-button>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="操作" width="240">
        <template #default="scope">
          <el-button type="primary" @click="pay(scope.row)" :disabled="scope.row.state !== '待支付'">支 付</el-button>
          <el-button type="danger" @click="returnPay(scope.row)" :disabled="scope.row.state !== '已支付'">退款</el-button>
          <el-popconfirm title="确定删除吗？" @confirm="handleDelete(scope.row.id)">
            <template #reference>
              <el-button size="default" type="danger">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    </el-card>
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[2,5,10,20]"
        :page-size="pageSize"
        layout="total,sizes,prev,pager,next,jumper"
        :total="total">
    </el-pagination>
  </div>
</template>

<script>
import request from "@/utils/request";
import { Edit,Remove,CirclePlus,Upload,Download,Search,Refresh,View,CircleClose } from '@element-plus/icons-vue';
export default {
  name: 'Order',
  components: {
    Edit,Remove,CirclePlus,Upload,Download,Search,Refresh,View,CircleClose
  },
  setup(){
    return{
      Edit,
      Remove,
      CirclePlus,
      Upload,
      Download,
      Search,
      Refresh,
      View,
      CircleClose
    }
  },
  data() {
    return {
      isShow:false,
      loading: true,
      form: {},
      dialogVisible: false,
      no: '',
      username:"",
      currentPage: 1,
      pageSize: 10,
      total: 0,
      tableData: [],
      ids:[],
      user: localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : {},
      // money:
    }
  },
  created() {
    // let userStr= localStorage.getItem("user") || "{}"
    // this.user= JSON.parse(userStr)
    //
    //
    // request.get("/api/user/"+this.user.id).then( res =>{
    //       if (res.code === '200'){
    //         this.user=res.data
    //       }
    //     }
    // )
    this.load();
  },
  methods: {
    tableRowStyle({ row, rowIndex }) {
      return { background:'#F2F6FC', color: '#0052d9', 'font-weight': 600 }
    },
    exportOrders() {
      location.href = "http://localhost:9090/orders/export";
    },
    handleUploadSuccess(res) {
      if (res.code === '200') {
        this.$message.success("导入成功")
        this.load()
      }
    },
    //wxpfjh9904@sandbox.com
    handleSelectionChange(val){
      console.log(this.ids)
      this.ids=val.map(v => v.id)
    },
    Show(){
      this.isShow=!this.isShow
    },
    deleteBatch(){
      if(!this.ids.length){
        this.$message.warning("请选择数据!")
        return
      }
      request.post("/orders/deleteBatch",this.ids).then(res=>{
        if(res.code === '200'){
          this.$message.success("批量删除成功")
          this.load()
        }else{
          this.$message.error(res.msg)
        }
      })
    },
    pay(row){
      window.open(`http://localhost:9090/alipay/pay?subject=${row.name}&traceNo=${row.no}&totalAmount=${row.total}`);
    },
    returnPay(row) {
      console.log(row)
      const url = `http://localhost:9090/alipay/return?totalAmount=${row.total}&alipayTraceNo=${row.alipayNo}&traceNo=${row.no}`
      request.get(url).then(res => {
        if(res.code === '200') {
          this.$message.success("退款成功")
        }  else {
          this.$message.error(res.msg)
        }
        this.load()
      })
    },
    load() {
      this.loading = true
      request.get("/orders", {
        params: {
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          no: this.no,
          username:this.username
        }
      }).then(res => {
           // this.loading = false
          console.log(res)
           this.tableData = res.records
           this.total = res.total
      })
    },
    reset(){
      this.no="";
      this.username="";
      this.load()
    },
    add() {
      this.dialogVisible = true
      this.form = {}
      if (this.$refs['upload']) {
        this.$refs['upload'].clearFiles()  // 清除历史文件列表
      }
    },
    save() {
      if (this.form.id) {  // 更新
        request.put("/orders", this.form).then(res => {
          console.log(res)
          if (res.code === '200') {
            this.$message({
              type: "success",
              message: "更新成功"
            })
          } else {
            this.$message({
              type: "error",
              message: res.msg
            })
          }
          this.load() // 刷新表格的数据
          this.dialogVisible = false  // 关闭弹窗
        })
      }  else {  // 新增
        request.post("/orders", this.form).then(res => {
          console.log(res)
          if (res.code === '200') {
            this.$message({
              type: "success",
              message: "新增成功"
            })
          } else {
            this.$message({
              type: "error",
              message: res.msg
            })
          }

          this.load() // 刷新表格的数据
          this.dialogVisible = false  // 关闭弹窗
        })
      }
    },
    handleEdit(row) {
      this.form = JSON.parse(JSON.stringify(row))
      this.dialogVisible = true
      this.$nextTick(() => {
        if (this.$refs['upload']) {
          this.$refs['upload'].clearFiles()  // 清除历史文件列表
        }
      })

    },
    handleDelete(id) {
      console.log(id)
      request.delete("/orders/" + id).then(res => {
        if (res.code === '200') {
          this.$message({
            type: "success",
            message: "删除成功"
          })
        } else {
          this.$message({
            type: "error",
            message: res.msg
          })
        }
        this.load()  // 删除之后重新加载表格的数据
      })
    },
    handleSizeChange(pageSize) {   // 改变当前每页的个数触发
      this.pageSize = pageSize
      this.load()
    },
    handleCurrentChange(pageNum) {  // 改变当前页码触发
      this.currentPage = pageNum
      this.load()
    }
  }
}
</script>
